/*
 * @Author: mayijun
 * @Date: 2022-05-19 09:44:43
 * @LastEditors: Zhang Kai
 * @LastEditTime: 2022-06-06 13:59:42
 */
//指标元信息管理
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch,
  computed
} from 'vue';
import Status from '@/components/status/index';
import './index.scss';
import Table from '@/components/Table/index';
import { ElMessage, ElMessageBox } from 'element-plus/lib/index';
import SearchForm from '@/views/indexManage/indexlib/base/components/searchForm';
import CustomColumn from '@/components/CustomColumn/index';
import { EFavoriteStatus, EPublishStatus } from '@/utils/constants';
import { useRouter } from 'vue-router';
import { CaretBottom } from '@element-plus/icons-vue';
import BatchOperates from '@/components/batchOperates/index.vue';
import shrinkLeft from '@/assets/images/shrinkLeft.svg';
import activeShrinkLeft from '@/assets/images/activeShrinLeft.svg';
import { ECustomColumn } from '@/utils/constants';
import API from '@/services';
import _ from 'lodash';
import ThemeTree from '@/components/ThemeTree';
import * as RouteNames from '@/router/consts';
import Bulk from '@/components/Bulk';

const AtomIndex = defineComponent({
  name: 'AtomIndex',
  components: { BatchOperates, CustomColumn },
  setup: (props, { slots, attrs, emit }) => {
    /* table List */
    const metricsList: any = reactive({
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      order: 2,
      sortBy: 'id'
    });

    // 当前选中节点
    const nodeInfo: any = ref({});

    // 分组key
    const groupKey = ref(1);

    // 选择row
    const multipleSelection: any = reactive({ data: [] });

    /* table loading */
    const TableLoading = ref(false);

    const router = useRouter();

    const formQuery = ref();

    const shrinkIcon = ref(shrinkLeft);

    /* 下载模版Url */
    const downloadUrl = ref('');

    //表格展示的字段
    const newTableColumn: any = ref([]);

    //自定义列
    const settings: any = ref([]);

    /* 收缩状态 */
    const toggle = ref(false);

    /* table Column */
    const tableColumn: any = ref([
      {
        keys: 1,
        sortable: true,
        minWidth: '80'
      },
      {
        keys: 11,
        sortable: true
      },
      {
        keys: 2,
        default: ({ row }: any) => (
          <a class="cnName" onClick={() => getDetailData(row.id)}>
            {row?.cnName}
          </a>
        )
      },
      {
        label: '状态',
        keys: 13,
        default: ({ row }: any) => (
          <Status
            color={statusCode(row.reviewStatus)}
            name={row.reviewStatusName}
          />
        )
      },
      {
        label: '操作',
        keys: 14,
        minWidth: '140',
        default: ({ row }: any) => {
          return (
            <div style={{ width: '100%' }}>
              <el-button
                type="text"
                onClick={() => getEditingData(row.id)}
                disabled={row?.reviewStatus == 5}
              >
                编辑
              </el-button>

              <el-button type="text" onClick={() => togglePublish(row)}>
                {row.reviewStatus == 5 ? '下线' : '发布'}
              </el-button>

              <el-dropdown
                onCommand={(command: string) => handleCommand(command, row)}
                trigger="click"
                v-slots={{
                  dropdown: () => (
                    <el-dropdown-menu class="derive-dropdown">
                      <el-dropdown-item command="collect">
                        {row.favoriteStatus === EFavoriteStatus.collected
                          ? '取消收藏'
                          : '收藏'}
                      </el-dropdown-item>
                      <el-dropdown-item disabled={!row.deletable} command="del">
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  )
                }}
              >
                <el-button type="text" style={{ marginLeft: '10px' }}>
                  更多
                  <el-icon color="#3C6EFF">
                    <CaretBottom />
                  </el-icon>
                </el-button>
              </el-dropdown>
            </div>
          );
        }
      }
    ]);

    //指标状态
    const statusCode = (code: number) => {
      switch (code) {
        case 1:
          return 'orange';
        case 3:
          return 'blue';
        case 5:
          return 'green';
        default:
          return '';
      }
    };

    /* 操作更多 */
    const handleCommand = (command: string, row: any) => {
      switch (command) {
        case 'collect':
          collectHandler(row);
          break;
        case 'del':
          remove(row.id);
          break;
        default:
          break;
      }
    };

    /* 发布 下线 */
    const togglePublish = (row: any) => {
      const isPublished = row.reviewStatus == 5;
      const text = isPublished ? '下线' : '发布';
      ElMessageBox.alert(`确认提交${text}申请吗`, `是否确认${text}该指标?`, {
        showCancelButton: true,
        confirmButtonText: `确认${text}`
      })
        .then(async () => {
          try {
            const { code, data } = await API.metrics.putMetricsPublishById({
              id: row.id,
              opType: isPublished
                ? +EPublishStatus.unpublish
                : +EPublishStatus.publish
            });
            if (code === 200) {
              ElMessage.success(`${text}成功`);
              getMetricsList(formQuery.value);
            }
          } catch (error) {
            ElMessage.error(`${text}失败`);
            console.log(error);
          }
        })
        .catch(() => {
          ElMessage.info(`取消${text}`);
        });
    };

    //查看页面
    const getDetailData = (id: any) => {
      router.push({
        name: RouteNames.ROUTE_INDEXMANAGEINFO,
        query: { id: id }
      });
    };

    /* 编辑 */
    const getEditingData = (id: number) => {
      router.push({
        name: RouteNames.ROUTE_INDEXMANAGEEDIT,
        query: { id: id }
      });
    };

    /* 删除 */
    const remove = async (id: number) => {
      ElMessageBox.alert('', '是否确认删除该指标?', {
        confirmButtonText: '确认删除',
        showCancelButton: true,
        confirmButtonClass: 'message-box-del'
      })
        .then(async () => {
          try {
            const { code, msg } = await API.metrics.deleteMetricsById({ id });
            if (code === 200) {
              ElMessage.success('删除成功');
              getMetricsList(formQuery.value);
            } else {
              ElMessage.warning(msg);
            }
          } catch (error) {
            ElMessage.error('删除失败');
            console.log(error);
          }
        })
        .catch(() => {
          ElMessage.info('取消删除');
        });
    };

    /* 收藏 */
    const collectHandler = async ({ favoriteStatus, id }: any) => {
      if (!favoriteStatus) {
        try {
          const { code } = await API.favoriteMetrics.getFavoriteMetricsById({
            id
          });
          code === 200 && ElMessage.success('收藏成功');
        } catch (error) {
          ElMessage.error('收藏失败');
          console.log(error);
        }
      } else {
        try {
          const { code } = await API.favoriteMetrics.putFavoriteMetricsById({
            id
          });
          code === 200 && ElMessage.success('取消收藏成功');
        } catch (error) {
          ElMessage.error('取消收藏失败');
          console.log(error);
        }
      }
      getMetricsList(formQuery.value);
    };

    /* 指标列表 */
    const getMetricsList = async (form?: any) => {
      try {
        TableLoading.value = true;
        const { pageNum, pageSize, order, sortBy } = metricsList;
        let subjectId = nodeInfo.value ? nodeInfo.value.id : '';
        const { code, data }: any = await API.metrics.getMetricsList({
          subjectId,
          pageNum,
          pageSize,
          order,
          sortBy,
          ...form
        });
        if (code === 200 && Array.isArray(data?.list)) {
          metricsList.list = data?.list;
          metricsList.total = +data?.total;
        }
      } catch (error) {
        console.log(error);
      } finally {
        TableLoading.value = false;
      }
    };

    const handleSelectionChange = (v: any) => {
      multipleSelection.data = v;
    };
    //批量操作回调
    const handleBatchOperate = async (v: any) => {
      //导入成功回调刷新
      if (v == undefined) {
        metricsList.pageNum = 1;
        getMetricsList(formQuery.value);
        return false;
      }
      if (multipleSelection.data.length === 0) {
        ElMessage.warning('请勾选操作项，再进行批量操作');
        return false;
      }
      let code, data;
      TableLoading.value = true;
      switch (v) {
        case 'publish':
          ({ code, data } = await API.metrics.putMetricsBatchPublish({
            ids: multipleSelection.data.map((d: any) => d.id),
            opType: 1
          }));
          if (code === 200) {
            ElMessage.success('批量发布成功');
          } else {
            // ElMessage.error('批量发布失败');
          }
          metricsList.pageNum = 1;
          getMetricsList(formQuery.value);
          break;
        case 'offline':
          ({ code, data } = await API.metrics.putMetricsBatchPublish({
            ids: multipleSelection.data.map((d: any) => d.id),
            opType: 2
          }));
          if (code === 200) {
            ElMessage.success('批量下线成功');
          } else {
            // ElMessage.error('批量下线失败');
          }
          metricsList.pageNum = 1;
          getMetricsList(formQuery.value);
          break;
        case 'collection':
          ({ code, data } =
            await API.favoriteMetrics.postFavoriteMetricsBatchCreate({
              ids: multipleSelection.data.map((d: any) => d.id)
            }));
          if (code === 200) {
            ElMessage.success('批量收藏成功');
          } else {
            // ElMessage.error('批量收藏失败');
          }
          metricsList.pageNum = 1;
          getMetricsList(formQuery.value);
          break;
        case 'cancel-collection':
          ({ code, data } =
            await API.favoriteMetrics.deleteFavoriteMetricsBatchCancel({
              ids: multipleSelection.data.map((d: any) => d.id)
            }));
          if (code === 200) {
            ElMessage.success('批量取消收藏成功');
          } else {
            // ElMessage.error('批量取消收藏失败');
          }
          metricsList.pageNum = 1;
          getMetricsList(formQuery.value);
          break;
        case 'delete':
          ElMessageBox.alert('', '是否确认删除已选指标?', {
            confirmButtonText: '确认删除',
            showCancelButton: true,
            confirmButtonClass: 'message-box-del'
          })
            .then(async () => {
              try {
                const { code, data, msg } =
                  await API.metrics.deleteMetricsBatchDelete({
                    ids: multipleSelection.data.map((d: any) => d.id)
                  });
                if (code === 200) {
                  ElMessage.success('批量删除成功');
                } else {
                  // ElMessage.error(msg);
                }
                metricsList.pageNum = 1;
                getMetricsList(formQuery.value);
              } catch (error) {
                console.log(error);
                // ElMessage.error('批量删除失败');
              }
            })
            .catch(() => {
              ElMessage.info('批量取消删除');
            });
          break;
      }
      TableLoading.value = false;
    };

    /* 保存自定义列表 */
    const customColumnConfirm = async (vo: any) => {
      try {
        const { code } = await API.userPageSetting.postSave({
          pageCode: ECustomColumn?.indexmanage,
          settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
            return {
              disabled,
              keys,
              isCheck,
              label,
              prop
            };
          })
        });
        if (code === 200) {
          ElMessage.success('保存配置成功');
          getCustomColumnApi();
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 获取自定义列列表 */
    const getCustomColumnApi = async () => {
      try {
        const { code, data }: any = await API.userPageSetting.getFindOne({
          pageCode: ECustomColumn?.indexmanage
        });
        if (code === 200) {
          settings.value = data?.settings;
          const checkArray = data?.settings?.filter((v: any) => v.isCheck);
          const column = checkArray.map((v: any, i: number) => {
            const columnIndex = tableColumn.value?.findIndex(
              (val: any) => val?.keys === v?.keys
            );
            return {
              minWidth: '200',
              ...tableColumn.value[columnIndex],
              ...v,
              fixed:
                i == checkArray.length - 1 && v.isCheck ? 'right' : undefined,
              columnKey: Date.now()
            };
          });
          column.unshift({
            type: 'selection',
            width: '55',
            isCheck: true
          });
          newTableColumn.value = _.compact(column);
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 排序 */
    const sortTable = (obj: any) => {
      if (obj.prop) {
        if (obj.order == 'ascending') {
          metricsList.order = 1;
        } else {
          metricsList.order = 2;
        }
        metricsList.sortBy = obj.prop;
      } else {
        metricsList.sortBy = 'id';
        metricsList.order = 2;
      }
      getMetricsList(formQuery.value);
    };

    onMounted(() => {
      getCustomColumnApi();
      //指标列表
      getMetricsList();
    });

    return () => {
      return (
        <div class="index_container">
          <div
            class="left-div"
            style={{ width: toggle.value ? '0px' : '210px' }}
          >
            <img
              class={toggle.value && 'shrinkRight'}
              onClick={() => (toggle.value = !toggle.value)}
              src={shrinkIcon.value}
              onMouseenter={() => (shrinkIcon.value = activeShrinkLeft)}
              onMouseout={() => (shrinkIcon.value = shrinkLeft)}
              alt=""
            />
            <ThemeTree
              groupKey={groupKey.value}
              titles="后台主题管理"
              isEdit={true}
              reviewStatusList={[]}
              onGetTreeNode={(treeNode: any) => {
                nodeInfo.value = treeNode;
                //指标列表
                getMetricsList(formQuery.value);
              }}
            ></ThemeTree>
          </div>
          <div class="right-div">
            <SearchForm
              search={(form: any) => {
                metricsList.pageNum = 1;
                metricsList.pageSize = 10;
                formQuery.value = form;
                getMetricsList(form);
              }}
            />
            <div class="table-operate">
              <div class="CustomColumn-operate-wrap">
                <CustomColumn
                  onConfirm={(v: any) => customColumnConfirm(v)}
                  tableColumn={settings.value}
                />
                <div class="checkLength">
                  已选择<b>{multipleSelection.data.length}</b>个指标
                </div>
              </div>
              <div class="batch-operate-wrap">
                <Bulk
                  downloadList={[
                    { command: 'atom', text: '原子指标下载' },
                    { command: 'deriva', text: '派生指标下载' },
                    { command: 'theme', text: '主题下载' }
                  ]}
                  onCommand={(val: any) => {
                    if (val == 'atom') {
                      downloadUrl.value = '/tmplate/download/1';
                    } else if (val == 'deriva') {
                      downloadUrl.value = '/tmplate/download/6';
                    } else {
                      downloadUrl.value = '/tmplate/download/5';
                    }
                  }}
                  downloadUrl={downloadUrl.value}
                  onSuccess={() => {
                    getMetricsList();
                    groupKey.value++;
                  }}
                />

                <BatchOperates
                  v-loading={TableLoading.value}
                  opKeys={[
                    'publish',
                    'offline',
                    'collection',
                    'cancel-collection',
                    'delete'
                  ]}
                  onBatchOperate={handleBatchOperate}
                  disabled={multipleSelection.data.length === 0}
                />
              </div>
            </div>
            <Table
              //height="calc(100vh - 340px)"
              onSortChange={sortTable}
              showCheckbox={true}
              v-loading={TableLoading.value}
              data={metricsList.list}
              column={newTableColumn.value}
              onSelectionChange={handleSelectionChange}
              onPageCurrentChange={(page: number) => {
                metricsList.pageNum = page;
                getMetricsList(formQuery.value);
              }}
              onPageSizeChange={(size: number) => {
                metricsList.pageNum = 1;
                metricsList.pageSize = size;
                getMetricsList(formQuery.value);
              }}
              pagination={{
                total: metricsList.total,
                currentPage: metricsList.pageNum,
                pageSize: metricsList.pageSize
              }}
            />
          </div>
        </div>
      );
    };
  }
});

export default AtomIndex;
